#include "grid.h"
#include <osg\Geometry>
#include <osg\Array>

namespace VrDataCore
{
	Grid::Grid(const osg::Vec3& center, float length, float width, int row, int col,const osg::Vec4& color,
		const QString& name):CoreBase::Transformable(NULL,name)
	{
		_gridGeode = new osg::Geode ;
		osg::StateSet *ss = new osg::StateSet ;
		ss->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
		osg::ref_ptr<osg::Geometry> _realgeo = new osg::Geometry ;
		_gridGeode->addDrawable( _realgeo ) ;
		_gridGeode->setStateSet(ss);
		osg::Vec3Array *cvertex = new osg::Vec3Array ;
		osg::DrawElementsUInt* indexset = new osg::DrawElementsUInt(osg::PrimitiveSet::LINES, 0);
		osg::Vec4Array *_colorsData = new osg::Vec4Array ; 	
		_colorsData->push_back(color) ;
		_colorsData->push_back(osg::Vec4(0.0, 0.0, 0.0, 1.0)) ;
		osg::TemplateIndexArray<unsigned int, osg::Array::UIntArrayType,4,4> *_colorsIndexData =
						new osg::TemplateIndexArray<unsigned int, osg::Array::UIntArrayType,4,4>;
		osg::Vec3 left_top_v( center._v[0]-width/2.0, center._v[1]+length/2.0 , center._v[2]) ;
		float rowstep = -length/row ;
		float colstep = width/col ;
		for( int r =0; r<=row; r++)
		{
			osg::Vec3 s = left_top_v  + osg::Vec3(0.0, r*rowstep, 0.0 ) ;
			osg::Vec3 e = left_top_v  + osg::Vec3(0.0, r*rowstep, 0.0 ) + osg::Vec3( width, 0.0 ,0.0 ) ;
			cvertex->push_back( s ) ;
			cvertex->push_back( e ) ;
			indexset->push_back( r*2 ) ;
			indexset->push_back( r*2 + 1 ) ;
			if( r == (row/2  ) ) {
				_colorsIndexData->push_back( 1 ) ;
				_colorsIndexData->push_back( 1 ) ;
			} else
			{
				_colorsIndexData->push_back( 0 ) ;
				_colorsIndexData->push_back( 0 ) ;
			}
		}
		int offindex = indexset->size() ;
		for( int c=0; c<=col; c++)
		{
			osg::Vec3 s = left_top_v  + osg::Vec3( c*colstep, 0.0, 0.0 ) ;
			osg::Vec3 e = left_top_v  + osg::Vec3( c*colstep, 0.0, 0.0 ) + osg::Vec3( 0.0, -length, 0.0 ) ;
			cvertex->push_back( s ) ;
			cvertex->push_back( e ) ;
			indexset->push_back( c*2 + offindex ) ;
			indexset->push_back( c*2 + 1 + offindex ) ;
			if( c == (col/2  ) ) {
				_colorsIndexData->push_back( 1 ) ;
				_colorsIndexData->push_back( 1 ) ;		
			} else
			{
				_colorsIndexData->push_back( 0 ) ;
				_colorsIndexData->push_back( 0 ) ;		
			}
		}
		_realgeo->setVertexArray( cvertex ) ;
		_realgeo->addPrimitiveSet(indexset);
		_realgeo->setColorArray(_colorsData) ;
		_realgeo->setColorIndices(_colorsIndexData) ;
		_realgeo->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
	}

	Grid::Grid(osg::MatrixTransform& node, CoreBase::ActorBase* owneractor,const QString& name)
		:CoreBase::Transformable(node,owneractor,name)
	{}

	Grid::~Grid()
	{}

	osg::Node* Grid::getOSGNode()
	{
		return _gridGeode.get();
	}

	const osg::Node* Grid::getOSGNode() const
	{
		return _gridGeode.get();
	}
}